package bigDecimal;

import org.javamoney.moneta.Money;
import org.junit.Test;

import javax.money.CurrencyUnit;
import javax.money.Monetary;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author wei.zhao
 * @description:
 * @date 2022年07月29日 9:56
 */
public class Demo {

    @Test
    // 使用浮点数运算会有精度丢失问题
    public void test01() {
        System.out.println(0.1 * 0.9);
    }

    @Test
    // new BigDecimal(0.1)不是0.1
    public void test02() {
        System.out.println(new BigDecimal(0.1));
        // 问题的解决
        System.out.println(BigDecimal.valueOf(0.1));
        System.out.println(new BigDecimal(Double.toString(0.1)));
    }

    @Test
    // 等值比较
    public void test03() {
        BigDecimal a = new BigDecimal("1.0");
        BigDecimal b = new BigDecimal("1.00");
        System.out.println(a.equals(b));
        System.out.println(a.compareTo(b));
    }

    @Test
    // 除不尽会抛异常
    public void test04() {
        BigDecimal a = new BigDecimal("1");
        BigDecimal b = new BigDecimal("3");
        try {
            System.out.println(a.divide(b));
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        System.out.println(a.divide(b, 2, RoundingMode.UP));
    }

    @Test
    // 转回String要小心
    public void test05() {
        BigDecimal d = BigDecimal.valueOf(12334535345456700.12345634534534578901);
        System.out.println(d.toPlainString());
        System.out.println(d.toString());
        System.out.println(d.toEngineeringString());
    }

    @Test
    // 乘法交换律失效
    public void test06() {
        BigDecimal a = BigDecimal.valueOf(1.0);
        BigDecimal b = BigDecimal.valueOf(3.0);
        BigDecimal c = BigDecimal.valueOf(3.0);
        System.out.println(a.divide(b, 2, RoundingMode.HALF_UP).multiply(c)); // 0.990
        System.out.println(a.multiply(c).divide(b, 2, RoundingMode.HALF_UP)); // 1.00
    }

    @Test
    // 金额计算更好的方式
    public void test07() {
        // 新建Money类
        CurrencyUnit cny = Monetary.getCurrency("CNY");
        Money oneYuan = Money.of(1.0, cny);
        Money oneYuan2 = Money.of(1.0, "CNY");
        System.out.println(oneYuan);
        System.out.println(oneYuan2);
        // 金额运算
        Money threeYuan = oneYuan.add(Money.of(2.0, "CNY"));
        System.out.println(threeYuan);
        Money tenYuan = oneYuan.multiply(10);
        System.out.println(tenYuan);
        Money fiveFen = oneYuan.divide(2);
        System.out.println(fiveFen);
        // 除不尽会保留很多位
        Money testYuan = oneYuan.divide(3);
        System.out.println(testYuan);
        // 比较相等
        System.out.println(oneYuan.equals(oneYuan2));
    }

}
